﻿// 后台脚本 - 管理插件的全局生命周期
import { Storage } from "@plasmohq/storage"

// 全局状态管理
interface GlobalState {
  isActive: boolean
  activeTabs: number[]
  startTime: number
  lastActivity: number
  totalSessions: number
  sessionId: string
}

// 创建存储实例
const storage = new Storage({
  area: "local"
})

// 插件状态
let pluginState: GlobalState = {
  isActive: false,
  activeTabs: [],
  startTime: Date.now(),
  lastActivity: Date.now(),
  totalSessions: 0,
  sessionId: ""
}

// 定时器引用
let heartbeatTimer: NodeJS.Timeout | null = null
let cleanupTimer: NodeJS.Timeout | null = null
let statePersistenceTimer: NodeJS.Timeout | null = null

// 心跳检测间隔（30秒）
const HEARTBEAT_INTERVAL = 30000
// 清理检查间隔（5分钟）
const CLEANUP_INTERVAL = 300000
// 状态持久化间隔（10秒）
const PERSISTENCE_INTERVAL = 10000

// 生成会话ID
function generateSessionId(): string {
  return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 初始化插件
async function initializePlugin() {
  // 从存储中恢复状态
  const savedState = await storage.get("pluginState")
  if (savedState && savedState.isActive) {
    // 恢复现有会话
    pluginState = { ...pluginState, ...savedState }
    pluginState.totalSessions++
  } else {
    // 创建新会话
    pluginState.totalSessions = 1
    pluginState.sessionId = generateSessionId()
  }
  
  pluginState.isActive = true
  pluginState.startTime = Date.now()
  pluginState.lastActivity = Date.now()
  
  // 保存状态
  await storage.set("pluginState", pluginState)
  
  // 启动心跳检测
  startHeartbeat()
  
  // 启动清理定时器
  startCleanupTimer()
  
  // 启动状态持久化
  startStatePersistence()
}

// 启动心跳检测
function startHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
  }
  
  heartbeatTimer = setInterval(async () => {
    pluginState.lastActivity = Date.now()
    
    // 检查是否有活跃标签页
    const tabs = await chrome.tabs.query({})
    pluginState.activeTabs = tabs.map(tab => tab.id!).filter(id => id !== undefined)
    
    // 保存状态
    await storage.set("pluginState", pluginState)
    
    // 发送心跳到所有标签页
    broadcastToAllTabs({
      type: "HEARTBEAT",
      data: {
        isActive: pluginState.isActive,
        sessionTime: Date.now() - pluginState.startTime,
        activeTabsCount: pluginState.activeTabs.length,
        sessionId: pluginState.sessionId
      }
    })
  }, HEARTBEAT_INTERVAL)
}

// 启动状态持久化
function startStatePersistence() {
  if (statePersistenceTimer) {
    clearInterval(statePersistenceTimer)
  }
  
  statePersistenceTimer = setInterval(async () => {
    // 定期保存状态，确保状态不丢失
    pluginState.lastActivity = Date.now()
    await storage.set("pluginState", pluginState)
  }, PERSISTENCE_INTERVAL)
}

// 启动清理定时器
function startCleanupTimer() {
  if (cleanupTimer) {
    clearInterval(cleanupTimer)
  }
  
  cleanupTimer = setInterval(async () => {
    // 检查是否需要清理
    const now = Date.now()
    const inactiveTime = now - pluginState.lastActivity
    
    // 如果超过10分钟没有活动，考虑清理
    if (inactiveTime > 600000) {
      await performCleanup()
    }
  }, CLEANUP_INTERVAL)
}

// 执行清理
async function performCleanup() {
  // 清理存储中的临时数据
  await storage.remove("tempData")
  
  // 重置活动状态
  pluginState.lastActivity = Date.now()
  await storage.set("pluginState", pluginState)
}

// 向所有标签页广播消息
async function broadcastToAllTabs(message: any) {
  try {
    const tabs = await chrome.tabs.query({})
    
    for (const tab of tabs) {
      if (tab.id) {
        try {
          await chrome.tabs.sendMessage(tab.id, message)
        } catch (error) {
          // 忽略无法发送消息的标签页（如chrome://页面）
        }
      }
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 处理来自popup或content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 使用立即执行的异步函数来处理await
  (async () => {
    try {
      switch (message.type) {
        case "GET_PLUGIN_STATE":
          // 更新活动状态
          pluginState.lastActivity = Date.now()
          await storage.set("pluginState", pluginState)
          sendResponse(pluginState)
          break
          
        case "UPDATE_ACTIVITY":
          pluginState.lastActivity = Date.now()
          await storage.set("pluginState", pluginState)
          sendResponse({ success: true })
          break
          
        case "REGISTER_TAB":
          if (sender.tab?.id && !pluginState.activeTabs.includes(sender.tab.id)) {
            pluginState.activeTabs.push(sender.tab.id)
            pluginState.lastActivity = Date.now()
            await storage.set("pluginState", pluginState)
          }
          sendResponse({ success: true })
          break
          
        case "UNREGISTER_TAB":
          if (sender.tab?.id) {
            pluginState.activeTabs = pluginState.activeTabs.filter(id => id !== sender.tab!.id)
            pluginState.lastActivity = Date.now()
            await storage.set("pluginState", pluginState)
          }
          sendResponse({ success: true })
          break
          
        case "BROADCAST_TO_ALL":
          await broadcastToAllTabs(message.data)
          sendResponse({ success: true })
          break
          
        case "RESET_SESSION":
          // 重置会话
          pluginState.sessionId = generateSessionId()
          pluginState.startTime = Date.now()
          pluginState.lastActivity = Date.now()
          await storage.set("pluginState", pluginState)
          sendResponse({ success: true, sessionId: pluginState.sessionId })
          break
          
        default:
          sendResponse({ error: "未知消息类型" })
      }
    } catch (error) {
      sendResponse({ error: error.message })
    }
  })()
  
  return true // 保持消息通道开放
})

// 监听标签页更新
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (changeInfo.status === "complete" && tab.url && !tab.url.startsWith("chrome://")) {
    // 标签页加载完成，注入内容脚本
    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        files: ["global-lifecycle.js"]
      })
      
      // 更新活动状态
      pluginState.lastActivity = Date.now()
      await storage.set("pluginState", pluginState)
    } catch (error) {
      // 静默处理错误
    }
  }
})

// 监听标签页创建
chrome.tabs.onCreated.addListener(async (tab) => {
  if (tab.id) {
    pluginState.activeTabs.push(tab.id)
    pluginState.lastActivity = Date.now()
    await storage.set("pluginState", pluginState)
  }
})

// 监听标签页移除
chrome.tabs.onRemoved.addListener(async (tabId) => {
  pluginState.activeTabs = pluginState.activeTabs.filter(id => id !== tabId)
  pluginState.lastActivity = Date.now()
  await storage.set("pluginState", pluginState)
})

// 监听浏览器启动
chrome.runtime.onStartup.addListener(() => {
  initializePlugin()
})

// 监听插件安装
chrome.runtime.onInstalled.addListener(() => {
  initializePlugin()
})

// 监听浏览器关闭前的清理
chrome.runtime.onSuspend.addListener(async () => {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
  }
  
  if (cleanupTimer) {
    clearInterval(cleanupTimer)
  }
  
  if (statePersistenceTimer) {
    clearInterval(statePersistenceTimer)
  }
  
  // 保存最终状态
  await storage.set("pluginState", {
    ...pluginState,
    isActive: false,
    lastActivity: Date.now()
  })
})

// 确保插件在启动时立即初始化
initializePlugin()

export {}
